import cv2
from flask import Flask, Response
from road_class import RoadClass
from pydub import AudioSegment
import simpleaudio as sa


app = Flask(__name__)

audio_map = {
    "level": AudioSegment.from_wav("/home/Code/RoboticDog/resource/pre_audio_file/level2wav.wav"),
    "stairs": AudioSegment.from_wav("/home/Code/RoboticDog/resource/pre_audio_file/stairs2wav.wav"),
    "overleap": AudioSegment.from_wav("/home/Code/RoboticDog/resource/pre_audio_file/overleap2wav.wav"),
    "slope": AudioSegment.from_wav("/home/Code/RoboticDog/resource/pre_audio_file/slope2wav.wav"),
}


def gen_frames():
    box_x, box_y = 420, 0
    box_width, box_height = 1080, 1080
    start_y = 20
    line_h = 18
    resize_x = 4

    rc = RoadClass(debug=True)
    status = "None"

    camera = cv2.VideoCapture(0)  # 0通常是内置摄像头的索引
    if not camera.isOpened():
        raise RuntimeError("无法打开摄像头")
    
    while True:
        success, frame = camera.read()  # 从摄像头读取一帧
        if not success:
            break
        else:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

            results, info = rc.infer(frame)

            cv2.rectangle(frame, (box_x, box_y), 
                (box_x + box_width, box_y + box_height), 
                (0, 255, 0), 2)
            
            frame = cv2.resize(frame, (960, 540))

            infos = info.split('\n')[:4]
            window1 = f"window1: {infos[1].split(', maxlen')[0].replace('windows: [deque(', '')}"
            window2 = f"window2: {infos[1].split('deque(')[-1].replace(', maxlen=10)]', '')}"
            infos_ = [infos[0], window1, window2, infos[2], infos[3]]
           
            for i, line in enumerate(infos_):
                y = start_y + i*line_h
                cv2.putText(frame, line, (10, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)
            
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()

            if status != results:
                status = results
                if status != 'None':
                    print("1111111111111111111111111111", status)
                    play_obj = sa.play_buffer(audio_map[status].raw_data, num_channels=audio_map[status].channels, bytes_per_sample=audio_map[status].sample_width, sample_rate=audio_map[status].frame_rate)
                    
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')  # 发送帧数据
    
    camera.release()  # 释放摄像头资源
 
@app.route('/video_feed')
def video_feed():
    return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
 
if __name__ == '__main__':
    print("[INFO]Access: http://192.168.1.100:5000/video_feed")
    
    app.run(host='192.168.1.100', port=5000)  # 在所有IP上运行，端口5000